package com.pearlsoft.webapp.core.dataset.factory.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.pearlsoft.commons.utils.ClassUtil;
import com.pearlsoft.webapp.core.dataset.DataSet;
import com.pearlsoft.webapp.core.dataset.DataSetException;
import com.pearlsoft.webapp.core.dataset.Field;
import com.pearlsoft.webapp.core.dataset.factory.AbstractDataSetFactory;

/**
 * 
 * JdbcDatasetFactory
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-10-25
 */
public class JdbcDatasetFactory extends AbstractDataSetFactory {

	protected JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public DataSet create(final String dsname) throws DataSetException {
		String type = (String) this.jdbcTemplate.query("select ds_type from judp_dataset where ds_name=?",
				new PreparedStatementSetter() {
					public void setValues(PreparedStatement ps) throws SQLException {
						ps.setString(1, dsname);
					}
				}, new ResultSetExtractor<String>() {
					public String extractData(ResultSet rs) throws SQLException, DataAccessException {
						if (rs.next()) {
							return rs.getString(1);
						}
						return null;
					}
				});
		try {
			final List<Field> fields = new ArrayList<Field>();
			this.jdbcTemplate.query("select name,type,length from judp_dataset_field where ds_name=?",
					new PreparedStatementSetter() {
						public void setValues(PreparedStatement ps) throws SQLException {
							ps.setString(1, dsname);
						}
					}, new RowCallbackHandler() {
						public void processRow(ResultSet rs) throws SQLException {
							Field field = new Field(rs.getString(1), rs.getString(2), rs.getInt(3));
							fields.add(field);
						}
					});
			final DataSet ds = (DataSet) ClassUtil.instance(type, new Object[] { dsname });
			ds.setFields(fields);
			return ds;
		} catch (Exception e) {
			throw new DataSetException(e);
		}
	}

}
